<!DOCTYPE html>
<html lang="en">
<head>
    <!-- 设置字符编码为 UTF-8 -->
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
    <script src="/webjars/sockjs-client/1.1.2/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/2.3.3/stomp.min.js"></script>
</head>
<body>
    <div id="messages"></div>

    <label for="nameInput"></label><input type="text" id="nameInput" placeholder="输入你的名字">
    <button onclick="sendMessage()">发送消息</button>
</body>
</html>
<script>
    let stompClient = null;

    function connect() {
        const socket = new SockJS('/ws');
        // 初始化 Stomp 客户端，连接到 WebSocket 服务器
        stompClient = Stomp.over(socket);
        // 禁用 STOMP 客户端的调试日志
        stompClient.debug = null;

        // 当客户端成功通过 WebSocket 连接到服务器后，会触发这个回调函数
        stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            // 订阅 /topic/greetings 主题
            stompClient.subscribe('/topic/greetings', function(message) {
                showMessage(JSON.parse(message.body).content);
            });

            // 订阅 /topic/time 主题
            stompClient.subscribe('/topic/time', function(message) {
                showMessage(JSON.parse(message.body).content);
            });

            // 订阅 /topic/broadcast 主题
            stompClient.subscribe('/topic/broadcast', function(message) {
                showMessage(JSON.parse(message.body).content);
            });
        });
    }

    function showMessage(message) {
        const div = document.createElement('div');
        div.textContent = message;
        document.getElementById('messages').appendChild(div);
    }

    function sendMessage() {
        const name = document.getElementById('nameInput').value;
        if (name) {
            // 向 /hello 发送消息
            stompClient.send("/app/hello", {}, JSON.stringify({'name': name}));
        }
    }

    // 发起连接
    connect();
</script>
</script>